import numpy as np
import matplotlib.pyplot as plt

# 设置中文支持
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

# 初始化路径
paths = [[7.0, 0.0]]  # 起始点

# 梯度下降
x, y = 7.0, 0.0
lr = 0.1  # 小于 0.5，安全
for _ in range(50):  # 多跑几步
    grad_x = 2 * x
    grad_y = 2 * y
    x -= lr * grad_x
    y -= lr * grad_y
    paths.append([x, y])

print(paths)
path = np.array(paths)

# 创建网格和等高线
x_min , x_max = path[:, 0].min() -1 , path[:,0].max() +1
print(x_min, x_max)
y_min , y_max = path[:,1].min() -1 , path[:,1].max() +1
print(y_min, y_max)
X, Y = np.meshgrid(np.linspace(-10, 10, 100), np.linspace(-10, 10, 100))
Z = X**2 + Y**2

# 绘图
plt.figure(figsize=(8, 8))
plt.contour(X, Y, Z, levels=20, alpha=0.6)
plt.plot(path[:, 0], path[:, 1], 'ro-', markersize=4, linewidth=2)
plt.scatter(0, 0, color='green', s=100, label='最小值')  # 标记极小值点
plt.xlabel('x')
plt.ylabel('y')
plt.title('梯度下降路径')
plt.legend()
plt.grid(True)
plt.show()